package com.leyou.item.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.user.dto.BrandDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryBrandService categoryBrandService;

    public BrandController(BrandService brandService, CategoryBrandService categoryBrandService) {
        this.brandService = brandService;
        this.categoryBrandService = categoryBrandService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryBrandById(@PathVariable("id") Long id){
        return ResponseEntity.ok(new BrandDTO(this.brandService.getById(id)));
    }

    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryBrandByIds(@RequestParam("ids") List<Long> idList){
        return ResponseEntity.ok(BeanHelper.copyWithCollection(this.brandService.listByIds(idList),BrandDTO.class));
    }

    @GetMapping("/page")
    public ResponseEntity<PageDTO<BrandDTO>> queryBrandByPage(
            @RequestParam(value = "key" ,required = false) String key,
            @RequestParam(value = "page" ,defaultValue = "1") Integer page,
            @RequestParam(value = "rows" ,defaultValue = "5") Integer rows
    ){
        return ResponseEntity.ok(brandService.queryBrandByPage(key,page,rows));
    }

    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brandDTO){
        brandService.saveBrand(brandDTO);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandOfCategory(@RequestParam("id") Long categoryId){
        return  ResponseEntity.ok(brandService.queryBrandOfCategory(categoryId));
    }

    /**
     * 修改品牌
     * @param brandDTO 品牌分类
     * @return 无
     */
    @PutMapping
    public ResponseEntity<Void> updateBrand(BrandDTO brandDTO) {
        brandService.updateBrand(brandDTO);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 删除品牌
     * @param id 要删除的品牌id
     * @return 无
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBrandById(@PathVariable("id") Long id){
        // 删除品牌表
        brandService.removeById(id);

        categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}

